<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class CategoryModel extends CI_Model 
{ 
	public $table = 'categories';
  	public $primary = 'category_id';
  
  	function add($data)
  	{
  		$this->db->insert($this->table, $data);
  	}
  	
  	function update($id, $data)
  	{
    	$this->db->where($this->primary, $id);
    	return $this->db->update($this->table, $data);
  	}
  	
	public function delete($id)
  	{
    	$this->db->where($this->primary, $id);
    	return $this->db->delete($this->table);
  	}
  	
    public function cnt() 
    {
        return $this->db->count_all($this->table);
    }
    
  	public function getCategories($limit, $start) 
    {
	    $this->db->limit($limit, $start);
	    $this->db->order_by($this->primary, 'desc');
	    $query = $this->db->get($this->table);
	    
	    return $query->result_array();
    }  
    
    //    function getAllCategories()
    //    {
    //      $query = $this->db->query("SELECT * FROM  `categories`
    //   								WHERE 1");
    //  	  return $query->result_array();
    //    }
    
    function getCategoryById($id)
    {
      $query = $this->db->query("SELECT * FROM  {$this->table}
      WHERE {$this->primary} = {$id}");
      return $query->row_array();
    }
  	
    /**
     * Frontend
     */
    
    /**
     * Trả lại tất cả các danh mục con của một cha chỉ ra
     * 
     * @param unknown_type $parent Id danh mục (menu) cha
     * @return array Mảng các danh mục con
     */
    function getAllCategories($parent = NULL)
    {
	    if (!is_null($parent)) {
	      	$this->db->where('parent_id', $parent);
	    }
	  	$query = $this->db->get('categories');
	  	$this->db->order_by($this->primary, 'ASC');
	  	return $query->result_array();
    } 
}